import path from "node:path";
import fs from "node:fs";
import { prefix } from "../enum/index.js";

export function resolveVuePathMap(root) {
  // 1.获取vue文件的路径
  const pathSfc = path.join(root, "node_modules");
  // 2.获取需要编译单文件组件的路径
  const compilerSFCPath = path.join(pathSfc, "@vue/compiler-sfc/package.json");
  // 3.读取package.json下面的module
  const fileName = JSON.parse(fs.readFileSync(compilerSFCPath, "utf8")).module;
  // 4.拼接全路径
  const compilerSFC = path.join(path.dirname(compilerSFCPath), fileName);

  function resolvePath(name) {
    return path.join(path.join(pathSfc, `@vue/${name}/dist/${name}.esm-bundler.js`));
  }

  const runtimeCore = resolvePath("runtime-core");
  const runtimeDom = resolvePath("runtime-dom");
  const shared = resolvePath("shared");
  const reactivity = resolvePath("reactivity");

  return {
    compilerSFC,
    "@vue/runtime-core": runtimeCore,
    "@vue/runtime-dom": runtimeDom,
    "@vue/shared": shared,
    "@vue/reactivity": reactivity,
    vue: runtimeDom,
  };
}

function ResolveVueModule({ app, root }) {
  const vuePathMap = resolveVuePathMap(root);
  app.use(async (ctx, next) => {
    await next();
    // 先判断是否以/node_modules开头的，如果是替换掉且去请求对应的路径资源
    if (ctx.path.indexOf(prefix) === 0) {
      const key = ctx.path.split(prefix)[1];
      const content = fs.readFileSync(vuePathMap[key], "utf8");
      ctx.type = "js";
      ctx.body = content;
    }
  });
}

export default ResolveVueModule;
